<template>
  <div class="login-container" :style="{backgroundImage: 'url(' + bgImgUrl + ')'}">
    <div class="login-panel">
      <div class="login-form-box">
        <div class="login-form-title" v-html="webTitle"></div>
        <el-form
          ref="loginForm"
          :model="loginFormData"
          :rules="rules"
          :validate-on-rule-change="false"
          @keyup.enter="submitForm"
        >
          <el-form-item label="用户名" prop="username" class="login-username">
            <el-input
              v-model="loginFormData.username"
              ref="usernameRef"
              placeholder="请输入用户名"
              @keyup.enter.stop="passwordRef.focus()"
            />
          </el-form-item>
          <el-form-item label="密　码" prop="password" class="login-password">
            <el-input
              v-model="loginFormData.password"
              ref="passwordRef"
              type="password"
              placeholder="请输入密码"
              @keyup.enter.stop="passwordEnter"
            />
          </el-form-item>
          <el-form-item v-if="showCaptcha" label="验证码" prop="captcha" class="login-captcha">
            <div class="captcha-box">
              <div>
                <el-input
                  v-model="loginFormData.captcha"
                  ref="captchaRef"
                  placeholder="请输入验证码"
                />
              </div>
              <div class="captcha">
                <img
                  v-if="captchaSrc"
                  :src="captchaSrc"
                  ref="captchaImg"
                  alt="请输入验证码"
                  @click="loginVerify()"
                />
              </div>
            </div>
          </el-form-item>
          <div class="login-button">
            <el-button
              type="primary"
              size="large"
              @click="submitForm"
            >登 录</el-button>
            <div v-if="setting.register === '1'" class="register-box">
              <span @click="register">立即注册</span>
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </div>

  <!-- 显示授权码 -->
  <el-dialog
    title="更新授权码"
    width="600px"
    v-model="licenseVisible"
    :close-on-press-escape="true"
    :close-on-click-modal="false"
    :show-close="false"
    destroy-on-close
    draggable
  >
    <el-form
      ref="licenseDataForm"
      class="no-padding"
      label-width="0"
      label-position="right"
      :model="licenseFormData"
      :rules="licenseRules"
    >
      <el-row>
        <el-col :span="24">
          <div>机器码：</div>
          <div class="machine-box">{{license.machineCode}}</div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div style="padding: 5px 0;">授权码：</div>
          <el-form-item label="" prop="license">
            <el-input type="textarea" :rows="8" v-model="licenseFormData.license"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button
        size="default"
        type="primary"
        @click="submitLicense"
        :loading="licenseEditLoading"
      >确定</el-button>
    </template>
  </el-dialog>

  <!-- 注册 -->
  <el-dialog
    v-model="registerVisible"
    :width="setting.registerWidth ? setting.registerWidth + 'px' : '600px'"
    :title="setting.registerTitle ? setting.registerTitle : '注册'"
    :close-on-click-modal="false"
    class="no-padding"
    destroy-on-close
    draggable
  >
    <div style="height: 100%;display: flex;flex-direction: column">
      <visual-page ref="registerRef" :pageInfo="registerPageInfo" />
    </div>
    <template #footer>
      <el-button
        size="default"
        type="primary"
        @click="submitRegister"
        :loading="registerLoading"
      >提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '@/http/api';
import { getSetting } from '@/utils/system';
import { useUserStore } from '@/pinia/modules/user';
import { onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import defaultBgImg from '@/assets/images/background.jpg';
import VisualPage from "@/visual/view/page.vue";
import tool from "@/utils/tool";

const imageUrl = ref(import.meta.env.VITE_IMAGE_PATH);
const userStore = useUserStore();
const setting = ref({});
const captchaSrc = ref('');

const loginForm = ref(null);
const showCaptcha = ref(false);
const bgImgUrl = ref('');
const webTitle = ref('系统登录');
const captchaImg = ref(null);
const loginFormData = ref({
  username: import.meta.env.VITE_USERNAME || '',
  password: import.meta.env.VITE_PASSWORD || '',
  captcha: '',
});
const rules = ref({
  username: [{ required: true, message: "请输入用户名", trigger: 'blur' }],
  password: [{ required: true, message: "请输入密码", trigger: 'blur' }],
  captcha: [{
    required: true,
    message: '验证码不能为空',
    trigger: 'blur',
  }],
});

const license = ref();
const licenseDataForm = ref();
const licenseFormData = ref({});
const licenseVisible = ref(false);
const licenseEditLoading = ref(false);
const licenseRules = ref({
  license: [
    {required: true, message: '请输入授权码', trigger: 'blur'},
  ]
});
const registerVisible = ref(false);
const registerLoading = ref(false);
const registerRef = ref();
const registerPageInfo = ref({});

const usernameRef = ref();
const passwordRef = ref();
const captchaRef = ref();

const passwordEnter = () => {
  if (captchaRef.value) {
    captchaRef.value.focus();
  } else {
    submitForm();
  }
};

const loginVerify = () => {
  api.captcha().then(res => {
    loginFormData.value.captcha = '';
    captchaSrc.value = URL.createObjectURL(new Blob([res.data]));
  });
};

const submitForm = async() => {
  loginForm.value.validate(async(result) => {
    if (result) {
      const data = Object.assign({}, loginFormData.value);
      const flag = await userStore.login(data);
      if (!flag) {
        if (!license.value.valid) {
          licenseVisible.value = true;
        }
        if (showCaptcha.value) {
          loginVerify();
        }
      }
    } else {
      ElMessage({
        type: 'error',
        message: '用户名/密码填写错误！',
        showClose: true,
      });

      if (showCaptcha.value) {
        loginVerify();
      }

      return false;
    }
  });
};

const loadLicense = () => {
  api.post("/license/queryBy").then(res => {
    license.value = res.data || {};
    if (!license.value.valid) {
      licenseVisible.value = true;
    }
  });
};

const register = () => {
  api.post(`/business/page/${setting.value.registerPageId}`).then(res => {
    registerPageInfo.value = res.data || {};
    registerVisible.value = true;
    registerLoading.value = false;
  });
};

const submitRegister = () => {
  registerRef.value.validate(valid => {
    if (!valid) return;
    registerLoading.value = true;
    api.runScript(setting.value.registerScriptId, registerRef.value.getData()).then(res => {
      ElMessage.success(res.message);
      registerVisible.value = false;
    }).catch(() => {
      registerLoading.value = false;
    });
  });
};

const submitLicense = () => {
  licenseDataForm.value && licenseDataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否更新授权码？', '提示', {type: 'info'}).then(() => {
        licenseEditLoading.value = true;
        api.post("/license/updateLicense", licenseFormData.value).then(res => {
          ElMessage.success(res.message);
          loadLicense();
          licenseVisible.value = false;
          licenseEditLoading.value = false;
        }).catch(() => {
          licenseEditLoading.value = false;
        });
      }).catch(()=>{});
    } else {
      ElMessage.error('数据录入不正确，请重新检查！');
    }
  });
};

const loadSetting = async() => {
  setting.value = await getSetting();
  setting.value = setting.value ? setting.value : {};
  bgImgUrl.value = !setting.value.loginBgImageId ? defaultBgImg : imageUrl.value + setting.value.loginBgImageId;
  showCaptcha.value = setting.value.loginCaptcha === '1' || false;
  webTitle.value = setting.value.webTitle || '系统登录';
  document.title = (setting.value.webTitle || '系统登录').split("<br/>")[0];

  if (setting.value.loginCss) {
    let style = document.createElement("style");
    style.textContent = setting.value.loginCss;
    document.head.appendChild(style);
  }

  if (showCaptcha.value) {
    loginVerify();
  }
};

onMounted(async() => {
  const user = await userStore.initUserInfo();
  if (user) {
    window.location.href = tool.getBaseUrl() + '/choose.html';
    return;
  }

  await loadSetting();
  loadLicense();
  usernameRef.value.focus();
});
</script>

<style lang="scss">
#app {
  background: #eee;
  height: 100vh;
  overflow: hidden;
}
.login-container {
  background-size: cover;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-end;

  .login-panel {
    margin-right: 200px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    .login-form-box {
      width: 320px;
      background-color: rgba(255, 255, 255, 0.5);
      padding: 40px 40px 20px 40px;
      border-radius: 10px;
      box-shadow: 2px 3px 7px rgba(0, 0, 0, .3);
      .login-form-title {
        display: flex;
        align-items: center;
        margin: 0  0 30px 0;
        font-size: 30px;
        font-weight: 600;
        justify-content: center;
      }
        .el-form-item__label {
          color: #000!important;
      }
      .captcha-box {
        display: flex;
        justify-content: space-between;
        width: 100%;
      }
      .captcha {
        width: 80px;
        height: 32px;
        margin-left: 8px;
        flex-shrink: 0;
        img {
          width: 100%;
          height: 100%;
          vertical-align: middle;
        }
      }
      .login-button {
        margin-top: 10px;
        text-align: right;
      }
    }
  }
}
.el-dialog .el-dialog__header {
  background-color: #268FF2 !important;
  border-bottom: 1px solid #e8e8e8 !important;
  padding: 15px 20px !important;
  display: flex !important;
  flex-direction: row !important;
  justify-content: center !important;
  align-items: center !important;
  margin-right: 0 !important;
}
.el-dialog .el-dialog__header .el-dialog__title {
  flex-grow: 1;
  color: white;
}
.el-dialog .el-dialog__header .el-dialog__headerbtn {
  position: unset;
  height: 16px!important;
  width: 16px!important;
}
.el-dialog .el-dialog__body {
  padding: 20px;
  min-height: 20vh!important;
  max-height: 70vh!important;
  flex: 1!important;
  -ms-flex: 1 1 auto!important;
  overflow-y: auto!important;
  overflow-x: hidden!important;
}
.el-dialog .el-dialog__footer {
  text-align: right!important;
  padding: 12px 10px 10px 10px!important;
  border-top: 1px solid #e8e8e8!important;
}
.machine-box {
  padding: 8px;
  background: #efefef;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin: 5px 0;
}
.register-box {
  cursor: pointer;
  margin-top: 15px;
}
@media screen and (max-width: 768px){
  .login-container {
    .login-panel {
      width: 100%;
      margin-right: unset;
      .login-form-box {
        width: unset;
      }
    }
  }
}
</style>